package thread.threadpool.example2;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * @Description: 练习工厂类ExecuTors的newFixedThreadPool(int nThreads)方法获取ExecutorService，然后调用submit方法，提交任务
 * 参数int nThreads 设置线程池的核心线程数量和线程池最大数量
 * @date: 2023/1/30 16:35
 * @author: Huangjunjie
 * @since JDK 1.8
*/
public class ExecuTorsTest2 {
    public static void main(String[] args) {
//        func1();
        func2();
    }

    /**
     * 使用 newFixedThreadPool方法得到线程池对象
     */
    private static void func1() {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            //执行线程
            executorService.submit(new MyRunnable(i));
        }
    }

    /**
     * 使用 newFixedThreadPool(int nThreads, ThreadFactory threadFactory)方法得到线程池对象
     */
    private static void func2() {
        //使用 newFixedThreadPool方法得到线程池对象
        ExecutorService executorService = Executors.newFixedThreadPool(3, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r);
            }
        });
        for (int i = 0; i < 10; i++) {
            //执行线程
            executorService.submit(new MyRunnable(i));
        }
    }
}
